import { Component, OnInit, Injector } from '@angular/core';
import { AppComponentBase } from '@shared/common/app-component-base';
import { NzTableHelper } from '@shared/helpers/NzTableHelper';
import { ServiceProxy } from '@shared/service-proxy/service-proxies';
import { finalize } from 'rxjs/operators';
import * as moment from 'moment';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Component({
  selector: 'app-path-time',
  templateUrl: './path-time.component.html',
  styleUrls: ['./path-time.component.less']
})
export class PathTimeComponent extends AppComponentBase implements OnInit {
  tableHelper: NzTableHelper;
  isVisible: boolean = false;
  sortStr: string = "desc";
  theTime: moment.Moment[] = [];
  sortList = [];
  ;
  constructor(
    injector: Injector,
    private _service: ServiceProxy,
    private httpClient: HttpClient) {
    super(injector);
    this.tableHelper = new NzTableHelper();
  }

  ngOnInit() {
    this.load();
    this.sortList = [
      { label: this.l("desc"), value: 'desc', checked: true },
      { label: this.l("asc"), value: 'asc' }];
  }

  load(pageIndex?: number) {
    if (typeof pageIndex !== 'undefined') {
      this.tableHelper.pageIndex = pageIndex || 1;
    }
    this.getList();
  }

  sort(sort: { key: string, value: string }): void {
    this.tableHelper.setSorting = sort;
    this.load();
  }

  getList() {
    this._service.arriveTimeCountUsingGET(this.tableHelper.pageSize, this.theTime[0], this.theTime[1], this.sortStr
    ).pipe(finalize(() => {
      this.tableHelper.loading = false;
    })).subscribe((result) => {
      this.tableHelper.items = result.result;
    });
  }


  reset() {
    this.theTime = [];
    this.sortStr = 'desc';
    this.load();
  }

  export() {
    this._service.exportPathUseUsingGET(this.tableHelper.pageSize, this.theTime[0], this.theTime[1], this.sortStr
    ).subscribe(m => {

    })
    // let url_ = this.baseUrl + "/api/center/statistics/route/exportPathUse?";
    //     if (limit !== undefined)
    //         url_ += "limit=" + encodeURIComponent("" + limit) + "&"; 
    //     if (startTime !== undefined)
    //         url_ += "startTime=" + encodeURIComponent(startTime ? "" + startTime.toJSON() : "") + "&"; 
    //     if (endTime !== undefined)
    //         url_ += "endTime=" + encodeURIComponent(endTime ? "" + endTime.toJSON() : "") + "&"; 
    //     if (sort !== undefined)
    //         url_ += "sort=" + encodeURIComponent("" + sort) + "&"; 
    //     url_ = url_.replace(/[?&]$/, "");


    //     let options_ : any = {
    //       observe: "response",
    //       responseType: "blob",
    //       headers: new HttpHeaders({
    //           "Content-Type": "application/json", 
    //       })
    //   };
  }

  formatSeconds(value) {
    var secondTime = parseInt(value);// 秒
    var minuteTime = 0;// 分
    var hourTime = 0;// 小时
    var day =0;
    if (secondTime > 60) {//如果秒数大于60，将秒数转换成整数
      //获取分钟，除以60取整数，得到整数分钟
      minuteTime = parseInt((secondTime / 60).toString());
      //获取秒数，秒数取佘，得到整数秒数
      secondTime = parseInt((secondTime % 60).toString());
      //如果分钟大于60，将分钟转换成小时
      if (minuteTime > 60) {
        //获取小时，获取分钟除以60，得到整数小时
        hourTime = parseInt((minuteTime / 60).toString());
        //获取小时后取佘的分，获取分钟除以60取佘的分
        minuteTime = parseInt((minuteTime % 60).toString());

        if (hourTime > 24) {
          //获取小时，获取分钟除以60，得到整数小时
          day = parseInt((hourTime / 24).toString());
          //获取小时后取佘的分，获取分钟除以60取佘的分
          hourTime = parseInt((hourTime % 24).toString());
        }
      }
    }
    var result = "" + parseInt(secondTime.toString()) + this.l("second");

    if (minuteTime > 0) {
      result = "" + parseInt(minuteTime.toString()) + this.l("minutes") + result;
    }
    if (hourTime > 0) {
      result = "" + parseInt(hourTime.toString()) + this.l("hours") + result;
    }
    if (day > 0) {
      result = "" + parseInt(day.toString()) + this.l("day") + result;
    }
    return result;
  }
  exportToExcel(): void {
    const nameValues: abp.INameValue[] = [];
    nameValues.push({ name: 'limit', value: this.tableHelper.pageSize });
    nameValues.push({ name: 'sort', value: this.sortStr});
    nameValues.push({ name: 'startTime', value: this.theTime[0]});
    nameValues.push({ name: 'endTime', value: this.theTime[1]});

    const queryString = abp.utils.buildQueryString(nameValues);
    const exportUrl = this.serviceIpUrl + '/api/center/statistics/route/exportPathUse' + queryString; // 以上为导出url的拼装，可自行拼装，直接一行拼起来也行

    const options: any = {
      responseType: 'blob',
      headers: new HttpHeaders({ 'Content-Type': 'application/json', 'Accept': 'application/json' })
    };

    this.httpClient.get(exportUrl, options).subscribe(res => {
      const blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' });// excel专用，其他请自行查阅资料
      const objectUrl = URL.createObjectURL(blob);
      const a = document.createElement('a');
      document.body.appendChild(a);
      a.setAttribute('style', 'display:none');
      a.setAttribute('href', objectUrl);
      const fileName = this.l('use__frequency_lock') + moment().format('YYYYMMDDHHmmss') + '.xlsx';
      a.setAttribute('download', fileName);
      a.click();
      URL.revokeObjectURL(objectUrl);

    });
  }

}
